<?php

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\components\BaseWechatController;
use app\components\Api;
use app\components\Wechat;
use app\components\Loyalty;
use app\components\Log;
use app\models\NewsList;
use app\models\Tenant;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\data\ArrayDataProvider;
use app\models\WechatLoginForm;
use app\models\NobelCampaign;
use app\models\NobelCampaignUser;
use yii\web\ServerErrorHttpException;
use app\components\PerformanceLog;
use app\models\PfLog;

class WechatController extends BaseWechatController
{
    // 微信服务器入口
    // 仅作为测试
    public function actionIndex()
    {
//         Log::debug('POST', $_POST);
//         Log::debug('GET', $_GET);
        if (array_key_exists('echostr', $_GET)) {
            // 微信服务器验证
            $this->valid();
        } else {
            // 接收微信消息及反馈
            $this->response();
        }
    }

    /**
     * 第三方授权处理
     * 请在设置OAuth链接的时候把要跳转的链接设置为state参数，把要跳转的方法设置为method参数
     * 请参考上面MenuSet()方法中设置$center_url的方式
     */
    public function actionOauth()
    {
    	Log::debug('WECHAT OAUTH GET FIELDS', $_GET);
    
    	// 删除session
    	$session = Yii::$app->session;
    	$session->destroy();
    	
    	// 记录开始时间
//     	if (isset($_GET['openid'])) {
//     		if ($_GET['appid'] == 'wx850dfb2f18b45451') {
//     			$pflog = new PfLog;
//     			$id = $pflog->begin($_GET['openid'], 'register');
//     			Yii::$app->session->set('pflog_id', $id);
//     		}
//     	}
    
    	if (empty($_GET['appid'])) {
    		throw new ServerErrorHttpException('appid not found');
    	}
    	
    	// 重要！获取appid，作为全局支持
    	$this->setAppid($_GET['appid']);
    
    	// 设置identifier
    	$tenant = Tenant::find()->where(['appid' => $_GET['appid']])->one();
    
    	if (empty($tenant->identifier)) {
    		throw new ServerErrorHttpException('identifier not found');
    	}
    	$this->setIdentifier($tenant->identifier);
    
    	// 设置loyalty config
    	if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
    		throw new ServerErrorHttpException('loyalty config not found');
    	} else {
    		$session = Yii::$app->session;
    		$loyaltyConfig = [
    		'tenant_id' => $tenant->tenant_id,
    		'app_id' => $tenant->appid,
    		'loyalty_accountid' => $tenant->loyalty_accountid,
    		'loyalty_username' => $tenant->loyalty_username,
    		'loyalty_password' => $tenant->loyalty_password,
    		'loyalty_url' => $tenant->loyalty_url,
    		];
    		$session->set('loyaltyConfig', $loyaltyConfig);
    	}
    
    	// 重要！获取openid，作为全局支持
    	if (empty($_GET['openid'])) {
    		throw new ServerErrorHttpException('openid not found');
    	}
    
    	$this->setOpenid($_GET['openid']); // 重要方法！把该用户的微信信息和Loyalty信息存到session中
    
    	// 使用获取的method参数跳转到对应的业务层
    	if (empty($_GET['method'])) {
    		throw new ServerErrorHttpException('method not found');
    	}
    	$method = str_replace('_', '/', $_GET['method']);
    
//     	Log::debug('WECHAT OAUTH SUCCESS');
//     	PerformanceLog::end();
    	// 如果有author_id
    	if (isset($_GET['author_id'])) {
    		return $this->redirect([$method, 'author_id' => $_GET['author_id'], 'openid' => $_GET['openid']]);
    	}
    	
    	if (isset($_GET['id'])) {
    		return $this->redirect([$method, 'id' => $_GET['id']]);
    	} else {
    		return $this->redirect([$method, 'oauth' => 'Y']);
    	}
    }

    public function actionDeleteUser()
    {
    	// 1
//     	$re = Loyalty::campaign_new(['campaign_type' => 'reward', 'campaign_name_c'=> '' ,'campaign_name' => '']);
//     	$this->bp($re);
//     	$re = Loyalty::generator(['hash' => 'campaign/Create_depreciation']);
    	//绑定campaign积分日期;
//     	$re = Loyalty::create_depreciation(['campaign_id' => '2', 'depreciation_type' => 'per_transaction', 'depreciation_interval' => '3',]);
//     	$re = Loyalty::list_point_rule();
		//创建points rule;
//     	$re = Loyalty::create_pointrule(['campaign_id' => 2, 'type' => 'points_bonus', 'value' => '500', 'level' => 'base', 'description' => '只是测试']);
		//修改points rule;
//     	$re = Loyalty::update_pointrule(['campaign_id' => 2, 'pointrule_id' => '2', 'type' => 'points_bonus']);
		//手动触发rule
//     	$re = Loyalty::trigger_earnrule(['code' => 'test27','event' => 'Customer Registration']);
//     	$re = Loyalty::get_list();
//     	$re = Loyalty::update_earnrule(['earnrule_id'=>'2', 'conditions'=>'{"match":[{"type":"model", "model":"AdvancedTransaction","attribute":"amount","value":"1"}]}']);
//     	$re = Loyalty::update_earnrule(['earnrule_id'=>'8', 'limit_per_customer' => '1']);
//     	$re = Loyalty::update_earnrule(['earnrule_id'=> '6', 'active' => 'yes']);
		//创建规则用户注册即发送优惠券
//     	$re = Loyalty::earnrule_create( // earnrule_id = 2; 29
//     			[
//     			'campaign_id' => 3,
//     			'active'=> 'no',
//     			'description' => 'Issue Personal Mirror poinits',
// //     			'txn_amount' => 0,
// //     			'trigger_on' => 'Customer Registration',
// //     			'event' => 'points test',
//     			'activity_rule' => 'all time',
// //     			'type' => 'token',
//     			]
//     	);
    	//把优惠券绑定到规则
//     	$re = Loyalty::add_rule_to_item(['earnrule_id' => '12', 'coupon_id' => '4', 'reward_qty' => '1']);
    	//把积分rule绑定到规则
//     	$re = Loyalty::add_rule_to_item(['earnrule_id' => '11', 'pointrule_id' => '2', 'reward_qty' => '1']);
//     	$re = Loyalty::list_earnrule();
//     	$identifier = $list_earnrule['Customer Registration'][0]['config']['identifier'];
// 		//给老用户发送优惠券
//     	$re = Loyalty::apply_reward(['code' => 'test21', 'reward_identifier' => $identifier]);
		//展示该用户所拥有的优惠券
//     	$data = ['code' => '001000115787','campaign_id' => '2'];
//     	$re = Loyalty::get_coupon_codes($data);
    	//从规则中删除优惠券
//     	$re = Loyalty::remove_rule_from_item(['earnrule_id' => 12,'coupon_id' => 4]);

//     	
		//创建从code center发送导入的优惠券 type = coupon, 'identifier'和code center的identifier对应;
//     	$re = Loyalty::coupon_create(['campaign_id' => 1, 'identifier' => 'jselect_test', 'name' => 'jselect test04', 'type' => 'coupon','description' => 'test', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-06-25', 'end_date' => '2018-08-25', 'store_id' => '001']);
    	//创建普通的优惠券 type = token, 'identifier'可以不填;
//     	$re = Loyalty::coupon_create(['campaign_id' => 1,  'autocreate' => 1, 'name' => '九折优惠券', 'type' => 'token','description' => '新会员注册', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-08-1', 'end_date' => "", 'store_id' => '1,2,3,4,5,6,7,8,9,10,11']);
//     	$re = Loyalty::coupon_create(['campaign_id' => 1,  'name' => '￥100','type' => 'token', 'barcode ' => 'DC00101823801', 'description' => 'full 2000 use','description_c' => '满2000使用', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-06-25', 'end_date' => '2019-08-25', 'store_id' => 001]);
    	
		//设置二维码展示同样的code
//     	$data_optional['pattern_type'] = 'fixed';
//     	$data_optional['fixed_value'] = 'DC00101823801';
//     	$re = Loyalty::coupon_create(['campaign_id' => 1, 'autocreate' => 1, 'barcode' => 'DC00101823801', 'name' => '￥100','type' => 'token','description' => 'full 2000 use','description_c' => '满2000使用', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-07-25', 'end_date' => '2019-07-25', 'store_id' => 001]);
    	   
//     	$re = Loyalty::coupon_update(['campaign_id'=> 1,  'coupon_id'=> 21, 'code_pattern' =>'{"pattern_type":"random","length":10,"prefix":"j_","suffix":"_x","codestring":"abcdefghijklmn"}', 'barcode_pattern' => json_encode($data_optional)]);
    	
//     	$re = Loyalty::coupon_update(['campaign_id'=> 1,  'coupon_id'=> 21, 'identifier' => ""]);
//     	$re = Loyalty::coupon_create(['campaign_id' => 1, 'autocreate' => 1, 'barcode' => 'DC00101823801', 'name' => '￥100','type' => 'token','description' => 'full 2000 use','description_c' => '满2000使用', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-07-25', 'end_date' => '2019-07-25', 'store_id' => 001]);

		//创建门店
//     	$re = Loyalty::store_create(['code' => 'JSDC01', 'storename'=> 'BJ WF Central' ,'redeem_password' => '0319', 'address1' => '北京市东城区王府井大街269号王府中环416A']);
//     	$re = Loyalty::store_create(['code' => 'JSPC04', 'storename'=> 'BJ Sesons place' ,'redeem_password' => '0525', 'address1' => '北京市西城区金融街金城坊街2号金融街购物中心B1层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC08', 'storename'=> 'BJ Solana' ,'redeem_password' => '0811', 'address1' => '北京市朝阳区朝阳公园路6号院1号楼M层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC07', 'storename'=> 'BJ Livat' ,'redeem_password' => '0621', 'address1' => '北京市大兴区欣宁街15号1号楼3层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC06', 'storename'=> 'BJ Hopson One' ,'redeem_password' => '0615', 'address1' => '北京市朝阳区西大望路甲22号院1号楼合生汇4层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC05', 'storename'=> 'BJ Joycity Chaoyang' ,'redeem_password' => '0818', 'address1' => '北京朝阳大悦城']);
//     	$re = Loyalty::store_create(['code' => 'BJSHUA', 'storename'=> 'BJ Shuangan' ,'redeem_password' => '0702', 'address1' => '北京市海淀区北三环西路38号双安商场5层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC02', 'storename'=> 'SH Isetan' ,'redeem_password' => '0328', 'address1' => '上海市静安区南京西路1038号6F']);
//     	$re = Loyalty::store_create(['code' => 'JSPC01', 'storename'=> 'SH DAIMARU' ,'redeem_password' => '0327', 'address1' => '上海市黄浦区南京东路228号6F']);
//     	$re = Loyalty::store_create(['code' => 'JSPC12', 'storename'=> 'SH Takashimaya' ,'redeem_password' => '0627', 'address1' => '上海市长宁区虹桥路1438号6F']);
//     	$re = Loyalty::store_create(['code' => 'JSPC11', 'storename'=> 'SH Raffles Changing' ,'redeem_password' => '0617', 'address1' => '上海市长宁区长宁路1139号长宁来福士B1']);
//     	$re = Loyalty::store_create(['code' => 'JSPC03', 'storename'=> 'SZ Wongtee' ,'redeem_password' => '0524', 'address1' => '深圳市福田区福华三路118号皇庭广场L1层']);
//     	$re = Loyalty::store_create(['code' => 'JSPC09', 'storename'=> 'GZ IGC' ,'redeem_password' => '0528', 'address1' => '广州市天河区兴民路222号天汇广场3层']);
//     	$re = Loyalty::store_get([]);
//     	$data = $re['result'];
//     	foreach ($data as  $k => $v){
//     		$store_id[] = $v['id'];
//     	}
//     	echo "<pre/>";
//     	var_dump($store_id);die;
//      $re = Loyalty::customer_search(['wechat_openid' => "o2Rmrt5U54B4kkWj5YfQ67g3V3xM"]);
//     	$re = Loyalty::customer_get(['mobile' => '8622941951494']);
		
//     	$re = $userIfno['result']['customers'];
    	
//     	foreach ($re as $k => $v){
//     		$code[] = $v['code'];
//     	}
//     	foreach ($code as $j){
//     		$dsa = Loyalty::customer_delete(['code' => 001000112610]);
//     	}
    	$re = Loyalty::customer_get(['mobile' => "8617821723428"]);
//     	$re = Loyalty::store_update(['code' => 'JSPC06', 'storename'=> 'BJ Hopson One', 'address1' => '北京市朝阳区西大望路甲22号院1号楼合生汇4层']);
//     	$re = Loyalty::trigger_earnrule(['code' => '001000115759', 'event' => 'Dyson Survey Coupon']);
//      $re = Loyalty::customer_update(['wechat_openid' => "",'code' => '0601000100000491418']);
//     	$re = Loyalty::customer_create(["code" => 'test001', "last_name" => "dada",'card_number' => '1111101d21112100a173114','mobile' => '8618723836813','wechat_openid' => 'o0ddadRdad1sddaam11-144E1rJL1ys86UEWXS8ZE']);
//         $re = Loyalty::customer_delete(['code' => '001000115787']);
//     	$re = Loyalty::coupon_detail(['campaign_id' => '1']);
//     	$re = Loyalty::list_coupon(['coupon_id' => 4]);
//     	$re = Loyalty::coupon_generate_codes(['generate_num' => 9999999, 'coupon_id' => '21']);
//     	$re = Loyalty::coupon_redeem(['coupon_code' => 'token.5b5972e170391', 'redeem_password' => 1234]);
//     	$re = Loyalty::customer_get(['mobile' => '8618723836813']);
//     	$re = Loyalty::customer_tnx_detail(['campaign_id' => 2, 'code' => 'test28', 'pagesize' => '10', 'pageno' => '1']);

        echo "<pre/>";
        var_dump($re);
    }

    public function actionTest()
    {	
		$model = "AdvancedCustomer";
    	$scenario = "get";
    	$config = '{
    "createdatetime": "createdatetime", 
    "modifydatetime": "modifydatetime", 
    "title": "title", 
    "first_name": "first_name", 
    "last_name": "last_name", 
    "phone": "phone", 
    "email": "email", 
    "email_status": "email_status", 
    "mobile": "mobile", 
    "state": "state", 
    "country_code": "country_code", 
    "mobile_status": "mobile_status", 
    "marketing_optout": "marketing_optout", 
    "gender": "gender", 
    "birthday": "birthday", 
    "birth_yyyy": "birth_yyyy", 
    "birth_mm": "birth_mm", 
    "birth_dd": "birth_dd", 
    "agegroup": "agegroup", 
    "wechat_openid": "wechat_openid", 
    "language": "language", 
    "street1": "street1", 
    "street2": "street2", 
    "district": "district", 
    "postal_code": "postal_code", 
    "city": "city", 
    "country": "country",
    "state" : "state", 
    "membership": {
        "accountid": "account_id", 
        "memberstatus": "status", 
        "code": "code", 
        "card_number": "card_number", 
        "entity_id": "entity_id", 
        "issuestore": "issue_store", 
        "tierid": "grade_id", 
        "tiername": "grade->label", 
        "monetaryto_nexttier": "gap_to_nextgrade", 
        "next_tier": "nextgrade", 
        "begindate": "date_begin", 
        "expirydate": "date_expiry", 
        "renewdate": "date_renew", 
        "previoustierid": "pre_grade_id", 
        "previousexpirydate": "pre_date_expiry", 
        "previousrenewdate": "pre_date_renew", 
        "gaptorenew": "gap_to_renew", 
        "opening_balance": "opening_balance", 
        "total_monetary": "amount", 
        "total_points": "points", 
        "tlv": "total_purchase"
    }
}';
    	$re = Loyalty::field_config();
//     	$re = Loyalty::create_model(['model' => $model,"scenario" => $scenario, 'config' => $config]);
//     	$re = Loyalty::campaign_new(['campaign_type' => 'reward', 'campaign_name_c'=> 'xxx' ,'campaign_name' => 'jselect test']);
//     	$re = Loyalty::store_create(['code' => '001', 'store_username'=> '捷成测试门店01' ,'store_password' => '1234']);
//     	$re = Loyalty::coupon_create(['campaign_id' => 30, 'identifier' => 'offer', 'name' => 'jselect test02', 'description' => 'Offer Coupon', 'usage_limit' => '1', 'number_of_coupons' => 'unlimited', 'start_date' => '2018-06-25', 'end_date' => '2018-08-25', 'store_id' => '001']);
//     	$re = Loyalty::customer_get(['wechat_openid' => 'o2Rmrt5U54B4kkWj5YfQ67g3V3xM']);
//     	$re = Loyalty::get_global();
//     	$re = Loyalty::update_global(['config' => $config,'name' => 'customer/get']);
//         $re = Loyalty::customer_create(['code' => '17713607873', 'wechat_openid' => 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0', 'first_name' => 'William', 'last_name' => 'Sun']);
//         $re = Loyalty::customer_update(['code' => '001002', 'wechat_openid' => 'o2Rmrt5U54B4kkWj5YfQ67g3V3xM']);
//         $re = Loyalty::customer_delete(['mobiel' => '8618623836813']);
//         $re = Loyalty::customer_create(['code' => "TEST008",'card_number' => 'TEST008','last_name' => 'bules','mobile' => '15308029844','wechat_openid' => 'o2Rmrt5r5C-axUzpV-Vh2zyDpIQA']);
        // echo strtotime("2018-01-21");
//         $re = Wechat::delete_card(['card_id' => 'p2Rmrt8dfl-HP78ycE-oFdL8rKlY']);
//     	$re = Wechat::geturl(['card_id' => 'p2RmrtxScDyRALt10AGgpKmzaNjk', 'outer_str' => '123']);
        // $this->bp(Wechat::ips());
        // $data = ['wechat_openid' => 'o'];
        // $code = '0601000100000490220';
        // $data = ['wechat_openid' => 'o0TqJuMsPSvBniRAyicU67FRGyO0'];
//         $re = Loyalty::customer_search(['mobile' => '8618723836813']);
//         $re = Loyalty::customer_delete(['code' => '6141770744964768']);
        // $re = Loyalty::customer_search($data);
        $this->bp($re);
        // print_r(Wechat::ips());
    }

    // 测试，后续删除
    public function actionTenantset()
    { 
        $this->setTenantId('william');
    }

    // 获取微信菜单
    public function actionMenuGet()
    {
        echo '<pre>';print_r(Wechat::menu_get());
    }

    public function actionKfcMenuSet()
    {
        $data = 
		[
			'button' =>
			[
                [
					'name' => '优惠与新品',
					'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => '新年上上签',
                            'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf6535e0fe0481adc&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=https://kfc-campaigns.xgatecorp.com/index.php/member/index&component_appid=wx5aec7706b086aa5b#wechat_redirect'
                        ],
                        [
                            'type' => 'view',
                            'name' => '手机优惠券',
                            'url' => 'https://login.kfc.com.cn/CRM/2015110324/coupons.html',
                        ],
                        [
                            'type' => 'view',
                            'name' => '移动积分兑换',
                            'url' => 'http://cmpay.jifenfu.net/cmpaym!productList.do?prov=&provider=kfc',
                        ],
                    ],
				],
				[
					'name' => 'WOW会员',
					'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => '会员码',
                            'url' => 'https://login.kfc.com.cn/CRM/2015110324/login.html',
                        ],
                        [
                            'type' => 'view',
                            'name' => '我的卡包',
                            'url' => 'https://login.kfc.com.cn/CRM/2015110324/cardbag.html',
                        ],
                        [
                            'type' => 'view',
                            'name' => 'K金商城',
                            'url' => 'https://login.kfc.com.cn/CRM/2015110324//crm.html',
                        ],
                        [
                            'type' => 'view',
                            'name' => '会员特权',
                            'url' => 'http://mall.kfc.com.cn/kfcmall20/wechat/index.do',
                        ],
                    ],
                ],
                [
                    'name' => '自助服务',
                    'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => '宅急送',
                            'url' => 'http://m.4008823823.com.cn/kfcmwos/index.htm?utm_source=kfcwechat&utm_medium=zzfw&utm_content=kfcorder&utm_campaign=ownmedia',
                        ],
                        [
                            'type' => 'view',
                            'name' => '自助点餐',
                            'url' => 'https://order.kfc.com.cn/mwos/?portalSource=WeChat&utm_source=WeChatCD',
                        ],
                        [
                            'type' => 'view',
                            'name' => '礼品卡|充200送50元券包',
                            'url' => 'http://login.kfc.com.cn/CRM/giftcard/index.html?from=singlemessage&isappinstalled=0',
                        ],
                        [
                            'type' => 'view',
                            'name' => '下载APP',
                            'url' => 'http://m.kfc.com.cn/superapp/index.html',
                        ],
                        [
                            'type' => 'view',
                            'name' => '附件门店',
                            'url' => 'http://m.kfc.com.cn/store/',
                        ],
                    ],
                ]
			],
        ];
        
        // echo '<pre>';print_r(Wechat::menu_set($data));
    }

 // 设置微信菜单
    public function actionMenuSet()
    {
        // 不能使用
        // exit;
        $appid = Wechat::config('appid');
        $component_appid = Wechat::config('component_appid');

        $personal_url = 'http://loyalty-portal.shadela.com/index.php/wechat/oauth';
        $minisite_url = 'http://loyalty-portal.shadela.com/index.php/minisite/oauth/id/5';// 此处id 号 为minisite_id ,需要打通				
        $redirect_personal = urlencode($personal_url);
        $redirect_minisite = urlencode($minisite_url);
        $personal_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_personal . '&response_type=code&scope=snsapi_base&state=personal#wechat_redirect';
        $minisite_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_minisite . '&response_type=code&scope=snsapi_base&state=minisite#wechat_redirect';

        // 第三方OAuth授权链接设置
        // 参考 config/web.php 中的 urlManager 的配置
        // 'wechat/oauth/<method:\w+>' => 'wechat/oauth',
        // method 参数的格式 controller_action
        $state = 'http://winshare.onthemooner.com/index.php/wechat/oauth/member_index';
//        $state = 'https://wechat.xgate.com/index.php/wechat/oauth/member_index';
        $center_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=' . $state . '&component_appid=' . $component_appid . '#wechat_redirect';

        // 轩客会的Oauth Url
        // $center_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx577957a019a2f435&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=https://wechat.xgate.com/index.php/wechat/oauth/member_index&component_appid=wx5aec7706b086aa5b#wechat_redirect';

        Log::debug('center_url', $center_url);

        // 昊祥科技测试会员中心连接
        $state = 'http://winshare.onthemooner.com/index.php/wechat/oauth/member_index';

        $hx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxeca2e361be1de14c' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'https://wechat.xgatecorp.com/index.php/wechat/oauth/member_index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $ws_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wx577957a019a2f435' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . $state . '&component_appid=' . $component_appid . '#wechat_redirect';

        $mo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxfe151ff0add3fb49' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . $state . '&component_appid=' . $component_appid . '#wechat_redirect';

        $mo_url_p = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxfe151ff0add3fb49' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'https://wechat.xgatecorp.com/index.php/wechat/oauth/member_index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $jc_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wx850dfb2f18b45451' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . $state . '&component_appid=' . $component_appid . '#wechat_redirect';

        $jc_url_p = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wx850dfb2f18b45451' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'https://wechat.xgatecorp.com/index.php/wechat/oauth/member_index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $kfc_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxeca2e361be1de14c' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'http://kfc.onthemooner.com/index.php/member/index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $kfc_url_production = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxf6535e0fe0481adc' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'https://kfc-campaigns.xgatecorp.com/index.php/member/index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $crabtree_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wxeca2e361be1de14c' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'http://crabtree.onthemooner.com/index.php/member/index' . '&component_appid=' . $component_appid . '#wechat_redirect';

        $cartnex_url = 'http://loyalty-portal.shadela.com/index.php/info';

        $liber_uat_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wx0e2e69eda478ec0e' .
            '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
            '&state=' . 'http://liber-uat.xgatecorp.com/member/index' . '&component_appid=' . $component_appid . '#wechat_redirect';
        
        $liber_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . 'wx0e2e69eda478ec0e' .
        		'&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base' .
        		'&state=' . 'https://liber.xgatecorp.com/member/index' . '&component_appid=' . $component_appid . '#wechat_redirect';
        $jcTest = 'https://mp.weixin.qq.com/bizmall/activatemembercard?action=preshow&&encrypt_card_id=CQ5YR2At32IdszqrtdWwVk15beqGCXP%2B4jEeQWpyIA8EvUZvMJ%2Fyxygdbfu8mfjg&outer_str=123&biz=MzA4MTQ0MzgwMQ%3D%3D#wechat_redirect';
        $data =
            [
            'button' =>
                [
                [
                    'type' => 'view',
                    'name' => '关于XGATE',
                    'url' => 'http://www.xgate.com',
                    'sub_button' => [],
                ],
                [
//                 'type' => 'view',
                'name' => 'JSELECT',
//                 'url' => $jcTest,
//                 'sub_button' => [],
                
                    'sub_button' => [
                        [
	                        'type' => 'view',
	                        'name' => 'JSELECT',
	                        'url' => $jcTest,
                        ],
                        [
                            'type' => 'view',
                            'name' => 'jselect测试',
                            'url' => $hx_url,
                        ],
                        
                        // [
                        //     'type' => 'view',
                        //     'name' => 'MOMO测试',
                        //     'url' => $mo_url,
                        // ],
                        // [
                        //     'type' => 'view',
                        //     'name' => 'JSELECT测试',
                        //     'url' => $jc_url,
                        // ],
                        // [
                        //     'type' => 'view',
                        //     'name' => 'JSELECT产品',
                        //     'url' => $jc_url_p,
                        // ],
                    ],
                ],
                [
                    'name' => 'Liber',
                    'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => 'Liber测试',
                            'url' => $liber_uat_url,
                        ],
                        [
                        'type' => 'view',
                        'name' => 'liber产品',
                        'url' => $liber_url,
                        ],
                    ],
                ]
            ],
        ];

        echo '<pre>';
        print_r(Wechat::menu_set($data));
    }

    /**
     * 新华文轩的诺贝尔奖推荐作者扫二维码入口
     * 已上线！
     */
    public function actionNobel()
    {
        // 生成短连接的OAuth二维码
        // $appid = Wechat::config('appid');
        // // $appid = 'wx577957a019a2f435'; //新华文轩
        // $component_appid = Wechat::config('component_appid');
        // // $state = 'https://wechat.xgate.com/index.php/wechat/oauth/wechat_nobel?author_id=5';
        // $state = 'http://winshare.onthemooner.com/index.php/wechat/oauth/wechat_nobel?author_id=1';
        // $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . 
        // '&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=' . $state . '&component_appid=' . $component_appid . '#wechat_redirect';
        // $short_url = $this->generateShortUrl($url);
        // echo $short_url;exit;

        // 接收author_id
        $author_id = Yii::$app->request->get('author_id');
        $openid = Yii::$app->request->get('openid');
        if (empty($author_id) || empty($openid)) {
            $wechat_url = 'https://mp.weixin.qq.com/s/kG0Xm8Q1NtB8Mg1ZFz5Ciw';
            return $this->redirect($wechat_url);
        }
        // $openid = $this->getOpenid();
        // $author_id = 1;
        // $openid = 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0';
        // $openid = 'o2RmrtyWd0sWb-MEhiEYs-N4YMN4';
        // 获取用户的微信信息
        $userinfo = Wechat::userinfo([$openid]);
        if (isset($userinfo['errmsg'])) {
            $userinfo['subscribe'] = 0;
        }

        // 把用户操作存到数据库
        $model = new NobelCampaign();
        $model->subscribe = $userinfo['subscribe'];
        $model->openid = $openid;
        $model->author_id = $author_id;
        $model->created_at = time();
        $model->save();

        // 如果是关注用户则存储用户信息
        $user = NobelCampaignUser::find()->where(['openid' => $openid])->one();
        if (!$user) {
            $user = new NobelCampaignUser();
        }
        $user->openid = $openid;
        $user->subscribe = $userinfo['subscribe'];
        // 如果是关注用户
        if ($userinfo['subscribe'] == 1) {
            $user->nickname = isset($userinfo['nickname']) ? $userinfo['nickname'] : '';
            $user->sex = isset($userinfo['sex']) ? $userinfo['sex'] : '';
            $user->city = isset($userinfo['city']) ? $userinfo['city'] : '';
            $user->country = isset($userinfo['country']) ? $userinfo['country'] : '';
            $user->province = isset($userinfo['province']) ? $userinfo['province'] : '';
            $user->headimgurl = isset($userinfo['headimgurl']) ? $userinfo['headimgurl'] : '';
            $user->subscribe_time = isset($userinfo['subscribe_time']) ? $userinfo['subscribe_time'] : '';
        }
        $user->save();
        // 跳转到微信图文消息
        $wechat_url = 'https://mp.weixin.qq.com/s/kG0Xm8Q1NtB8Mg1ZFz5Ciw';
        Log::debug('author_id', $author_id);

        if ($author_id == '6' || $author_id == 6) {
            $wechat_url = 'https://mp.weixin.qq.com/s/605ywAUYWpp80mR-RVJYow';
        }

        Log::debug('wechat_url', $wechat_url);
        return $this->redirect($wechat_url);
    }

    /**
     * 生成微信短链接
     * @param string $url
     * @return short_url or false
     */
     private function generateShortUrl($url)
     {
         $short_url = Wechat::short(['action' => 'long2short', 'long_url' => $url]);
         if ($short_url['errmsg'] == 'ok') {
             return $short_url['short_url'];
         } else {
             return false;
         }
     }

    /**
    **显示图文列表界面
    */
    public function actionNewsIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => NewsList::find(),
        ]);

        return $this->render('newsindex',['model' => $dataProvider]);
    }

    /**
     * 查看指定文章的评论数据
     * $msg_data_id 图文id
     * $count 获取评论数量
     * $type  获取评论类型
     */

    public function actionDetails()
    {
       $id = Yii::$app->request->get('id');
       $result = NewsList::find()->where(['id' => $id])->one();
       $count = 30;
       $type = 0;
       $data = ['msg_data_id' => $result->msg_data_id, 'begin' =>'0','count' =>$count,'type' =>$type];
       $comment = Wechat::comment_list($data);
       var_dump($comment);die;
    } 

    //图文总数据
     public function actionGetNewsTotal()
    {
        if (Yii::$app->request->isPost){
        $datas = Yii::$app->request->post('daterange');
        $data = explode ('-',$datas);
        $startime = str_replace('/','-',$data[0]);
        $endtime = str_replace('/','-',$data[1]);
        $time = ['begin_date' =>$startime,'end_date' =>$endtime];
        $result = Wechat::get_user_read($time);
        // $result = Wechat::get_article_total($time);
        if (!empty( $result['list'])){
            $row = $result['list'];
            return $this->render('get-user-read',['row' => $row]);
        }else{
            echo "<pre>";die;
        }
        }
        return $this->render('newstotal');
    }
    /**
     * 获取图文永久素材列表批量插入数据库
     */
    public function getNewslist($type,$offset,$count)
    {
        $data = ['type' => $type,'offset' => $offset,'count' => $count];
        $newslist = Wechat::material_batch_get($data);
        $result = $newslist['item'];
        $res =  array_column($result,'media_id','update_time');
        foreach($res as $key=>$value){
            $arr[] = ['msg_data_id' =>$value ,'updatetime' =>$key];
        }
        Yii::$app->db->createCommand()->batchInsert('wx_newslist', ['msg_data_id', 'updatetime'], $arr)->execute();
        }

        public function actionQrcode()
        {
        
        //  echo 'success';
        $openid = $this->getOpenid();
        echo $openid;
        $data = [$openid]; 
        var_dump(Wechat::userinfo($data));die;
    }

    public function actionWechatlogin()
    {

    //    $openid = 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0';
//        bob
        $login = ['username'=>'1232','password'=>'bob']; 
        // $data = Loyalty::customer_get(['code'=>15928713252]);
        $data = Loyalty::login($login);
        echo "<pre>";
        var_dump($data);die;
        $openid = 'o2Rmrt1YzfsbZEzpvcNMuqwXoNxs';
        $this->setOpenid($openid);
        $openid = $this->getOpenid();
        // $openid = 'o2Rmrt1YzfsbZEzpvcNMuqwXoNxs';
        $model = new WechatLoginForm();
        $model->login($openid);
        // return $this->goBack();
    }
    
    public function actionCreateMember()
    {
    	$data = [
    	'card' => [
	    	'card_type' => 'MEMBER_CARD',
	    	'member_card' => [
		    	'background_pic_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHdH4pibDImtNukZVkoXywuRlYyHpVmywFxVpibH7RaUs8RjEibaenzsbUJZHicZlA7uYsFDbXV9OymNfw/0?wx_fmt=png',
		    	'base_info' => [
			    	'logo_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHdH4pibDImtNukZVkoXywuRlI8YfyS3MQjD5tHDtkaSTSJO6k8sx4kTKr6ZsoIyWxBNUcg8eycianJA/0?wx_fmt=png', // 卡券的商户logo，建议像素为300*300 必填
			    	'code_type' => 'CODE_TYPE_BARCODE', // Code展示类型 必填 (显示二维码)
			    	'brand_name' => 'J SELECT ', // 商户名字,字数上限为12个汉字 必填
			    	'title' => '会员卡', // 卡券名，字数上限为9个汉字 必填
			    	'color' => 'Color030', // 券颜色。按色彩规范标注填写Color010-Color100 必填
			    	'notice' => '付款时请向工作人员出示会员卡', // 卡券使用提醒，字数上限为16个汉字 必填
			    	'description' => '该会员卡仅限会员本人使用', // 卡券使用说明，字数上限为1024个汉字 必填
// 			    	'service_phone' => '', // 客服电话
			    	'sku' => [
			    		'quantity' => 100000000, // 卡券库存的数量 必填
			    	],
			    	'date_info' => [
			    		'type' => 'DATE_TYPE_PERMANENT', // 永久有效类型 必填
			    	],
// 			    	'bind_openid' => 'false',//不需要指定用户
// 			    	'custom_url_name' => '我的资料',
// 			    	'custom_url' => 'https://wechat.xgatecorp.com/index.php/member-binding/member-profile?appid=wxeca2e361be1de14c',
// 			    	'custom_url_sub_title' => '',
// 			    	'promotion_url_name' => '会员卡详情',
// 			    	'promotion_url' => 'https://wechat.xgatecorp.com/index.php/member-binding/member-card-info?appid=wxeca2e361be1de14c',
// 			    	'use_all_locations' => true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
			    	'get_limit' => 1, // 每人可领券的数量限制，建议会员卡每人限领一张 选填
// 			    	"use_custom_code" => true,
			    	"can_give_friend" => false,
			    	// 'pay_info' => [ // 选填
			    	//     'swipe_card' => [ // 选填
			    	//         'is_swipe_card' => true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
			    	//         // 'is_pay_and_qrcode' => ($model->is_pay_and_qrcode == 1) ? false : true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
			    	//     ],
			    	// ],
//     				'can_give _friend' => 'fasle',//不能转赠
		    	],
		    	"custom_field1" => [
			    	"name" => "积分",
			    	"url" => "javascript:;",
		    	],
		    	"custom_field2" => [
			    	"name_type" => "FIELD_NAME_TYPE_COUPON",
			    	"url" => "https://wechat.xgatecorp.com/index.php/member-binding/coupon-list?appid=wxeca2e361be1de14c"
		    	],
// 		    	'custom_cell1' => [
// 		    		'name' => '品牌介绍',
// 		    		'tips' => '了解我们',
// 		    		'url' => 'https://mp.weixin.qq.com/s/H8UJi7rjhd_O9JuIFb9YRA'
// 		    	],
		    	// 'advanced_info' => [],
		    	'prerogative' => '1. 注册即成为J SELECT会员；
								  2. J SELECT会员可不定期获得会员专属优惠；
								  3. J SELECT会员可优先获取新品推荐及门店活动资讯。', // 会员卡特权说明,限制1024汉字 必填
		    	'supply_bonus' => false, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
		    	'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
		    	'wx_activate' => true, // 设置激活方式为 一键激活
		    	'wx_activate_after_submit' => true, // 设置为一键激活中的跳转激活
		    	'wx_activate_after_submit_url' => 'https://wechat.xgatecorp.com/index.php/member-binding/new-member?appid=wxeca2e361be1de14c', // 设置用户跳转激活后的地址为
		    	// 'bonus_rule' => [ // 选填
		    	//     'cost_money_unit' => '1', // 消费金额,以分为单位
		    	//     'increase_bonus' => '1', // 对应增加的积分
		    	//     'max_increase_bonus' => '5', // 用户单次可获取的积分上限
		    	//     'init_increase_bonus' => '10', // 初始设置积分
		    	//     'cost_bonus_unit' => '1', // 每使用多少积分
		    	//     'reduce_money' => '1', // 抵扣xx元，（这里以分为单位）
		    	//     'least_money_to_use_bonus' => '1', // 抵扣条件，满xx元（这里以分为单位）可用
		    	//     'max_reduce_bonus' => '10', // 抵扣条件，单笔最多使用xx积分
		    	// ],
		    	],
    		],
    	];
    	echo "<pre/>";
    	$card = Wechat::card_create($data);
    	var_dump($card);
    	die;
    }

    public function actionUpdateMember()
    {
    	$data = [
    	// 'card_id' => "p2Rmrt3QSQbzKUNYXtE9zgmOysFM",
    	//             'card_id' => "p2RmrtxeU9xuLfXoEbFJFPLQf4kI",
    	'card_id' => 'p2RmrtxScDyRALt10AGgpKmzaNjk',
    	//                'card_type' => 'MEMBER_CARD',
    	'member_card' => [
		    	'background_pic_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHdH4pibDImtNukZVkoXywuRlYyHpVmywFxVpibH7RaUs8RjEibaenzsbUJZHicZlA7uYsFDbXV9OymNfw/0?wx_fmt=png',
		    	'base_info' => [
			    	'logo_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHdzSt6J3h809ribFFVBCc8vhbDSngZgxGiauRsjEoJtAGhhEbGnvicW3r0qpk9GUKWOEAzfAl8j0shFw/0?wx_fmt=png', // 卡券的商户logo，建议像素为300*300 必填
			    	'code_type' => 'CODE_TYPE_BARCODE', // Code展示类型 必填 (显示二维码)
// 			    	'brand_name' => 'J SELECT ', // 商户名字,字数上限为12个汉字 必填
			    	'title' => '会员卡', // 卡券名，字数上限为9个汉字 必填
			    	'color' => 'Color030', // 券颜色。按色彩规范标注填写Color010-Color100 必填
			    	'notice' => '付款时请向工作人员出示会员卡', // 卡券使用提醒，字数上限为16个汉字 必填
			    	'description' => '该会员卡仅限会员本人使用', // 卡券使用说明，字数上限为1024个汉字 必填
			    	'use_all_locations' => true,
// 			    	'service_phone' => '', // 客服电话
// 			    	'sku' => [
// 			    		'quantity' => 100000000, // 卡券库存的数量 必填
// 			    	],
// 			    	'date_info' => [
// 			    		'type' => 'DATE_TYPE_PERMANENT', // 永久有效类型 必填
// 			    	],
// 			    	'bind_openid' => 'false',//不需要指定用户
			    	'custom_url_name' => '个人资料',
			    	'custom_url' => 'https://wechat.xgatecorp.com/index.php/member-binding/member-profile?appid=wxeca2e361be1de14c',
			    	'custom_url_sub_title' => '',
			    	
			    	'promotion_url_name' => '最新活动',
			    	'promotion_url' => 'http://cn.mikecrm.com/2mepS8U',
			    	'use_all_locations' => true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
			    	'get_limit' => 1, // 每人可领券的数量限制，建议会员卡每人限领一张 选填
			    	// 'pay_info' => [ // 选填
			    	//     'swipe_card' => [ // 选填
			    	//         'is_swipe_card' => true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
			    	//         // 'is_pay_and_qrcode' => ($model->is_pay_and_qrcode == 1) ? false : true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
			    	//     ],
			    	// ],
		    	],
		    	
			    	"custom_cell1" => [
				    	"name" => "",
				    	"tips" => "",
				    	"url" => ""
			    	],
// 		    	"custom_field1" => [
// 		    		"name" => "积分",
// 		    		"url" => "https://wechat.xgatecorp.com/index.php/member-binding/error?appid=wxeca2e361be1de14c",
// 		    	],
		    	"custom_field1" => [
			    	"name" => "",
			    	"url" => "",
		    	],
		    	"custom_field2" => [
			    	"name_type" => "FIELD_NAME_TYPE_COUPON",
			    	'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeca2e361be1de14c&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=https://wechat.xgatecorp.com/index.php/wechat/oauth/member_coupon&component_appid=wx5aec7706b086aa5b#wechat_redirect',
// 			    	"url" => "https://wechat.xgatecorp.com/index.php/member-binding/coupon-list?appid=wxeca2e361be1de14c"
		    	],
// 		    	'custom_cell1' => [
// 		    		'name' => '品牌介绍',
// 		    		'tips' => '了解我们',
// 		    		'url' => 'https://mp.weixin.qq.com/s/H8UJi7rjhd_O9JuIFb9YRA'
// 		    	],
		    	// 'advanced_info' => [],
		    	'prerogative' => '1. 注册即成为J SELECT会员；
								  2. J SELECT会员可不定期获得会员专属优惠；
								  3. J SELECT会员可优先获取新品推荐及门店活动资讯。', // 会员卡特权说明,限制1024汉字 必填
		    	'supply_bonus' => false, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
		    	'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
		    	'wx_activate' => true, // 设置激活方式为 一键激活
		    	'wx_activate_after_submit' => true, // 设置为一键激活中的跳转激活
		    	'wx_activate_after_submit_url' => 'https://wechat.xgatecorp.com/index.php/member-binding/new-member?appid=wxeca2e361be1de14c', // 设置用户跳转激活后的地址为
		    	// 'bonus_rule' => [ // 选填
		    	//     'cost_money_unit' => '1', // 消费金额,以分为单位
		    	//     'increase_bonus' => '1', // 对应增加的积分
		    	//     'max_increase_bonus' => '5', // 用户单次可获取的积分上限
		    	//     'init_increase_bonus' => '10', // 初始设置积分
		    	//     'cost_bonus_unit' => '1', // 每使用多少积分
		    	//     'reduce_money' => '1', // 抵扣xx元，（这里以分为单位）
		    	//     'least_money_to_use_bonus' => '1', // 抵扣条件，满xx元（这里以分为单位）可用
		    	//     'max_reduce_bonus' => '10', // 抵扣条件，单笔最多使用xx积分
		    	// ],
		    	],
    	];
    	echo "<pre/>";
    	$card = Wechat::card_update($data);
    	var_dump($card);
    	die;
    }
    
    public function actionWechatinfo()
    {
        $appid = "wxeca2e361be1de14c";
        $mchid = "1368056102";
        $key = "54e7209f2cd5408d679e546a99e95c51";
        $non_str = '5K8264ILTKCH16CQ2502SI8ZNMTM67V3';
        $long_url = 'weixin://wxpay/bizpayurl?sign=5K8264ILTKCH16CQ2502SI8ZNMTM67V2&appid=wxeca2e361be1de14c&mch_id=1368056102&product_id=159287&time_stamp=15928713&nonce_str=5K8264ILTKCH16CQ2502SI8ZNMTM67V3';
        $result = ['appid'=>$appid,'mch_id'=>$mchid,'nonce_str'=>$non_str,'long_url'=>$long_url];
        $str = $this->MakeSign($result,$key);
        // var_dump($str);die;
        // $sign_datas = ['mch_id'=>$mchid,'nonce_str'=>'5K8264ILTKCH16CQ2502SI8ZNMTM67V4','sign'=>$str];
        // $sign = Wechat::get_signkey($sign_datas);
        // // var_dump($sign);die;
        // $sign_key =strtoupper($sign['sandbox_signkey']);
        // // var_dump($sign_key);die;
        // $sign_key= "ca2e4416e79b48a7c8b1e5e336679804";        
        // $a = ['sign'=>$sign_key];
        // $nonce_strs = ['mch_id'=>$mchid,'nonce_str'=>'5K8264ILTKCH16CQ2502SI8ZNMTM67VS'];
        // $sign_un =  $this->MakeSign($nonce_strs,$sign_key);
        // var_dump($sign);die;
        $loadbilldata = [
            'appid'=>$appid,
            'mch_id'=>$mchid,
            'nonce_str'=>$non_str,
            'long_url'=>$long_url,
            'sign'=>$str,
        ];
        // var_dump(Api::toxml($loadbilldata));die;
        $loadbill = Wechat::short_url($loadbilldata);
        echo "<pre>";
        var_dump(json_encode(($loadbill)));die;

    }
    // 微信sigin算法
    /**
	 * 生成签名
	 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	public function MakeSign($sign,$key)
	{
        //签名步骤一：按字典序排序参数
        ksort($sign);       
        $string = $this->ToUrlParams($sign);
        // var_dump($string);die;
		//签名步骤二：在string后加入KEY
        $string = $string . "&key=".$key;
        // var_dump($string);die;
		//签名步骤三：MD5加密
        $string = md5($string);
        // var_dump($string);die;
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
    }
    /**
	 * 格式化参数格式化成url参数
	 */
	public function ToUrlParams($sign)
	{
		$buff = "";
		foreach ($sign as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
    }
    public function actionIndexnobel()
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeca2e361be1de14c&redirect_uri=https%3A%2F%2Fwcapi.xgatecorp.com%2Fwechat%2Fauth%2Furl&response_type=code&scope=snsapi_base&state=http://winshare.onthemooner.com/index.php/wechat/oauth/nobel_index&component_appid=wx5aec7706b086aa5b#wechat_redirect';
        $row = $this->generateShortUrl($url);
        echo "<pre>";
        var_dump($row);die;
    }

    public function actionSetRecord(){
//                $re = Loyalty::campaign_list();
//        echo "<pre/>";
//        var_dump($re);die;
        $wechatInfo = $this->getWechatInfo();
        $userInfo = $this->getUserInfo();
        //        echo "<pre/>";
//        var_dump($userInfo);die;
        $time = date("Y-m-d H:i:s",time());
//        echo $time;die;
        $re = Loyalty::transaction_record(['code' => '0601000100000491525', 'campaign_id' => 2, 'transaction_datetime' => $time, 'amount' => '1000']);
        echo "<pre/>";
        var_dump($re);die;
    }

    public function actionDeleteRecord()
    {
        $re = Loyalty::transaction_delete(["invoiceno" => "",'code' => '33146','campaign_id' => 2]);
        echo "<pre/>";
        var_dump($re);die;
    }

    public function actionUse()
    {
        $re = Loyalty::transaction_redeem(["points_to_redeem" => "100",'code' => '0601000100000491525','campaign_id' => 2]);
        echo "<pre/>";
        var_dump($re);die;
    }
    
    public function actionPush()
    {
//     	$data = [
//     		'type' => 'image',
//     		'offset' => '0',
//     		'count' => '20',
//     	];
//     	$re = Wechat::material_batch_get($data);
//     	$this->bp($re);
    	
//     	$data = [
//     		'touser' => 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0',
//     		'msgtype' => 'text',
//     		'text' => ['content' => 'Hello'],
//     	];
    	
//     	$data = [
// 	    	'touser' => 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0',
// 	    	'msgtype' => 'text',
// 	    	'text' => ['content' => '<a href="http://www.qq.com" data-miniprogram-appid="wx21921adc25a4b7fe" data-miniprogram-path="pages/index/index">点击跳小程序</a>'],
//     	];
    	
    	$data = [
	    	'touser' => 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0',
	    	'msgtype' => 'miniprogrampage',
	    	'miniprogrampage' => [
	    		'title' => 'This is a test message',
	    		'appid' => 'wx21921adc25a4b7fe',
	    		'pagepath' => 'pages/index/index',
	    		'thumb_media_id' => 'oYY6ADktygV1EllQUCiFrmdb71cUkhlc4PFDMJ8nMm4',
	    	],
    	];
    	$re = Wechat::custom_send($data);
    	$this->bp($re);
    }
}
